package chapter2;

/**
 * 算法基础-二进制数相加
 */
public class Add {

    public static int[] add(int[] a, int[] b) {
        int[] c = new int[a.length + 1];
        // 进位
        int bit = 0;
        // 末位相加
        int i = a.length - 1, j = i + 1;
        while (i >= 0) {
            // 当前位
            int curr = 0;
            if (a[i] == 1 && b[i] == 1) {
                curr = 1;
                bit = 1;
            }
            if (a[i] == 1 || b[i] == 1) {
                curr = 1;
            }
            if (curr == 1 && bit == 0) {
                c[j] = 1;
            }
            if (curr == 0 && bit == 1) {
                c[j] = 1;
                bit = 0;
            }
            // a==1,b==1 ：进位保留,c[j]=0

            i--;
            j--;
        }
        c[0] = bit;

        return c;
    }

}
